//
//  MyShowAllListViewController.m
//  BosidengIphone
//
//  Created by  on 11-12-30.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyShowAllListViewController.h"
#import "MyShowData.h"
#import "SyncImageView.h"
#import "MyShowDetailViewController.h"
#import "MainViewController.h"
#import "AppDelegate.h"
#import "MyShowItemsXmlParser.h"
#import "SyncRequestParseOperation.h"

@implementation MyShowAllListViewController
@synthesize allDatas;
@synthesize labTitle;
@synthesize scrollView;
@synthesize waitView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [waitView release];
    [scrollView release];
    [labTitle release];
    [allDatas release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)initImageButtonView:(MyShowData *)data andFrame:(CGRect)frame andIndex:(NSInteger)index {
    UIView *rootView = [[UIView alloc] initWithFrame:frame];
    [scrollView addSubview:rootView];
    [rootView release];
    
    NSString *imageUrl = data.smallImage;
    SyncImageView *imageView = [[SyncImageView alloc] initWithUrl:imageUrl andRequestQueue:requestQueue];
    imageView.frame = rootView.bounds;
    [rootView addSubview:imageView];
    [imageView release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = rootView.bounds;
    button.tag = 100 + index;
    [rootView addSubview:button];
    [button addTarget:self action:@selector(imageClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)jumpToShowDetailView:(MyShowData *)data {
    MyShowDetailViewController *detailView = [[MyShowDetailViewController alloc] initWithNibName:@"MyShowDetailViewController" bundle:nil];
    detailView.data = data;
    [(MainViewController *)mainViewController pushViewController:detailView];
    [detailView release];
}

- (void)imageClick:(id)sender {
	UIButton *imageButton = (UIButton *)sender;
	int index = imageButton.tag - 100;
    MyShowData *data = [allDatas objectAtIndex:index];
    [self jumpToShowDetailView:data];
}

- (void)initView {
    int paddingX = 8, paddingY = 10;
    int imageWidth = 96, imageHeight = 96;
    int cols = 3;
    
    int x = 0, y = 0;
    int rowIndex = 0, colIndex = 0;
    CGRect frame;
    MyShowData *data;
    for (int i = 0; i < [allDatas count]; i++) {
        rowIndex = i % cols;
        colIndex = ceilf(i / cols);
        x = rowIndex * (imageWidth + paddingX);
        y = colIndex * (imageHeight + paddingY);
        frame = CGRectMake(x, y, imageWidth, imageHeight);
        data = [allDatas objectAtIndex:i];
        [self initImageButtonView:data andFrame:frame andIndex:i];
    }
    scrollView.contentSize=CGSizeMake(320, y+imageHeight);
    
    labTitle.text = [NSString stringWithFormat:@"%@(%d)", [AppDelegate getLanguageString:@"show_all_show"], allDatas.count];
}

- (void)updateLocalAllShowList:(NSArray *)serviceData {
    for (int i = 0; i < [serviceData count]; i++) {
        NSDictionary *data = [serviceData objectAtIndex:i];
        NSString *uid = [data objectForKey:@"ShowID"];
        MyShowData *localData = [MyShowData getItemByID:uid];
        if (localData == nil) {
            localData = [[[MyShowData alloc] init] autorelease];
        } else {
            //判断是否需要删除本地图片
            NSString *localImages = localData.smallImage;
            NSString *serviceImages = [data objectForKey:@"SmallImage"];
            if (![localImages isEqualToString:serviceImages]) {
                [localData removeSmallImage];
            }
            
            localImages = localData.bigImage;
            serviceImages = [data objectForKey:@"BigImage"];
            if (![localImages isEqualToString:serviceImages]) {
                [localData removeBigImage];
            }
        }
        //NSLog(@"save new data(%@)", localData);
        //添加，更新最新的数据
        [localData setValue:data];
        [localData save];
    }
    //取得最新的数据集
    NSArray *localDatas = [MyShowData getAllItems];
    for (MyShowData *data in localDatas) {
        NSString *localId = data.showID;
        if ([self isNeedDeleteItem:localId serviceData:serviceData serviceKey:@"ShowID"]) {
            //NSLog(@"delete not exist data(%@)", data);
            [data removeBigImage];
            [data removeSmallImage];
        }
    }
}

- (void)syncRequestParseStatusNofity:(ParseData *)parseData {
    int status = parseData.status;
    if (status == kParseDataFailed) {
        NSLog(@"getShow Request Failed! Reason:%@", parseData.error);
    } else {
        NSArray *datas = [parseData.data objectForKey:@"items"];
        [self updateLocalAllShowList:datas];
    }
    self.allDatas = [MyShowData getAllItems];
    [self initView];
    [waitView stopAnimating];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [waitView startAnimating];
    
    NSString *url = [NSString stringWithFormat:@"%@/GetAllShow.ashx", [AppDelegate serviceUrl]];
    MyShowItemsXmlParser *showParser = [[MyShowItemsXmlParser alloc] init];
    SyncRequestParseOperation *operation = [[SyncRequestParseOperation alloc] initWithURLString:url xmlParser:showParser delegate:self];
    //[operation setUserInfo:[self setRequestName:key]];
    [requestQueue addOperation:operation];
    [operation release];
    [showParser release];
    //NSLog(@"request AllShowList url = %@", url);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.labTitle = nil;
    self.scrollView = nil;
    self.waitView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
